#!/usr/bin/env python3
"""
GL论坛搜索工具 - 基于fastMCP框架
"""

import asyncio
import json
import logging
from typing import Dict, Any, Optional

import httpx
from pydantic import BaseModel, Field

from config import Config

# 配置日志
logger = logging.getLogger(__name__)

class GetRelativePostRequest(BaseModel):
    """获取相关帖子请求模型"""
    topic: str = Field(description="主题关键词")

class GLForumClient:
    """GL论坛RPC客户端"""
    
    def __init__(self, rpc_endpoint: str):
        self.rpc_endpoint = rpc_endpoint
        self.session = httpx.AsyncClient(timeout=30.0)
    
    async def get_relative_posts(self, topic: str) -> Dict[str, Any]:
        """调用论坛内部RPC接口获取相关帖子"""
        if Config.MOCK_MODE:
            return self._mock_relative_posts(topic)
        
        try:
            # 构造RPC请求
            rpc_request = {
                "jsonrpc": "2.0",
                "method": "get_relative_postrequest",
                "params": {
                    "topic": topic
                },
                "id": 1
            }
            
            # 发送RPC请求
            response = await self.session.post(
                self.rpc_endpoint,
                json=rpc_request,
                headers={"Content-Type": "application/json"}
            )
            response.raise_for_status()
            
            result = response.json()
            
            # 检查RPC响应
            if "error" in result:
                logger.error(f"RPC调用失败: {result['error']}")
                return self._mock_relative_posts(topic)
            
            return result.get("result", {})
            
        except Exception as e:
            logger.error(f"GL论坛RPC调用失败: {e}")
            return self._mock_relative_posts(topic)
    
    def _mock_relative_posts(self, topic: str) -> Dict[str, Any]:
        """模拟相关帖子数据"""
        return {
            "posts": [
                {
                    "id": f"post_{i+1}",
                    "title": f"关于{topic}的讨论 {i+1}",
                    "content": f"这是一个关于{topic}的详细讨论帖子。包含了相关的技术细节和实践经验分享。",
                    "author": f"用户{i+1}",
                    "created_at": f"2024-01-{15+i:02d}T10:30:00Z",
                    "replies_count": (i+1) * 5,
                    "views_count": (i+1) * 100,
                    "url": f"https://forum.example.com/posts/post_{i+1}"
                } for i in range(5)
            ],
            "total_count": 5,
            "topic": topic
        }
    
    async def close(self):
        """关闭HTTP会话"""
        await self.session.aclose()

# 创建GL论坛客户端实例
gl_client = GLForumClient(Config.RPC_ENDPOINT)

async def gl_forum_search(
    topic: str
) -> str:
    """
    在GL论坛中搜索相关帖子
    
    Args:
        topic: 要搜索的主题关键词
    
    Returns:
        相关帖子列表的格式化字符串
    """
    try:
        # 调用RPC接口获取相关帖子
        result = await gl_client.get_relative_posts(topic)
        
        posts = result.get("posts", [])
        total_count = result.get("total_count", 0)
        
        if not posts:
            return f"❌ 没有找到关于 '{topic}' 的相关帖子。"
        
        # 格式化输出
        formatted_posts = []
        for post in posts:
            post_text = (
                f"**{post['title']}**\n"
                f"👤 作者: {post['author']}\n"
                f"📅 发布时间: {post['created_at']}\n"
                f"💬 回复数: {post['replies_count']} | 👀 浏览数: {post['views_count']}\n"
                f"📝 内容摘要: {post['content'][:100]}{'...' if len(post['content']) > 100 else ''}\n"
                f"🔗 链接: {post['url']}"
            )
            formatted_posts.append(post_text)
        
        header = f"🔍 GL论坛搜索结果 (主题: '{topic}', 共找到 {total_count} 个相关帖子)\n" + "="*60 + "\n\n"
        return header + "\n\n".join(formatted_posts)
        
    except Exception as e:
        logger.error(f"GL论坛搜索时发生错误: {e}")
        return f"❌ 搜索失败: {str(e)}"

# 清理资源
async def cleanup():
    """清理资源"""
    await gl_client.close()

if __name__ == "__main__":
    # 测试代码
    async def test_search():
        result = await gl_forum_search("Python编程")
        print(result)
        await cleanup()
    
    asyncio.run(test_search())